<!--
 * @Descripttion: 新增销售单
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-17 20:26:23
 * @LastEditors: cxguo
 * @LastEditTime: 2020-11-12 16:19:20
 -->
<template>
  <div class="bill_container">
    <affix>
      <div class="clearfix paddingLR20">
        <div class="oper-button btn-group fl">
          <SelectGoodsBtns
            :price-cat-name="defaultPriceCatName"
            :price-cat="defaultPriceCat"
            :show-tab-names="['all','hot']"
            @on-select-sure="onSelectGoodsSure"
          />
        </div>
        <div class="oper-button btn-group fr">
          <el-button type="default" @click="btnJump2List">历史单据</el-button>
          <el-button type="primary" :loading="btnLoading.save" @click="btnSave">保存(Ctrl+S)</el-button>
          <el-button type="default" :loading="btnLoading.save" @click="btnSave({readd:true})">保存并新增(F9)</el-button>
        </div>
      </div>
    </affix>
    <el-main>
      <el-form
        ref="billForm"
        :model="dataObj"
        :rules="ruleValidator"
        label-position="left"
        inline
        label-width="80px"
      >
        <el-card shadow="never">
          <div slot="header" class="header clearfix">
            <div class="clearfix">
              <div class="fl">
                <el-form-item
                  label="客户"
                  label-width="50px"
                  prop="comegoId"
                >
                  <SelectComego
                    ref="comego"
                    v-model="dataObj.comegoId"
                    class="w150"
                    :default-value="dataObj.comegoName"
                    @change="onCustomerChange"
                  />
                </el-form-item>
              </div>
              <div class="fr">
                <el-form-item class="white-border" label="单据编号: " prop="billNo">
                  <el-input v-model="dataObj.billNo" class="w150" size="mini" />
                </el-form-item>
              </div>
            </div>
            <div class="title">
              <h1> 商品销售单 </h1>
            </div>
          </div>
          <div class="clearfix">
            <div class="fl">
              <span>销售类型：</span>
              <el-select
                v-model="billExtSale.type"
                style="width:100px;"
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in optionsData.saleType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <!-- <el-checkbox v-model="dataObj.isPrint" label="保存后打印" border style="margin-right:0" /> -->
              <el-checkbox v-model="billExtSale.isDelivery" true-label="1" false-label="0" label="送货" border style="margin:0;" />
              <!-- <el-checkbox v-model="billExtSale.isInvoice" true-label="1" false-label="0" label="需要发票" border style="margin:0;" /> -->
            </div>
            <div class="fr">
              <el-form-item label="经手人:" prop="handUserId">
                <SelectEmployee
                  v-model="dataObj.handUserId"
                  is-inc-guide
                  :is-set-default="true"
                />
              </el-form-item>
              <el-form-item label="业务日期:">
                <el-date-picker v-model="dataObj.businessTime" value-format="yyyy-MM-dd HH:mm:ss" class="w150" type="datetime" />
              </el-form-item>
            </div>
          </div>
          <DeliveryInfo v-show="billExtSale.isDelivery === '1'" v-model="billExtSale" />
          <goods-select
            ref="GoodsSelect"
            :is-open-discount="isOpenDiscount"
            :is-open-tax="isOpenTax"
            :tax-rate="taxRate"
            :price-cat="priceCats"
            :default-price-cat="defaultPriceCat"
          />
          <div class="bottom">
            <table class="table" border="1" cellspacing="0" cellpadding="0">
              <tr>
                <td align="right" @mouseenter="onTdMouseEnter" @mouseleave="onTdMouseLeave">
                  <div class="w500">
                    <el-form-item class="white-border">
                      <discount v-model="dataObj.discountType" />
                      <el-input v-model="dataObj.discountValue" class="w100" />
                    </el-form-item>
                    <el-form-item label="其他费用:" class="white-border">
                      <el-input v-model="dataObj.amountOther" class="text-right" />
                    </el-form-item>
                  </div>
                </td>
                <td :width="tableFixedWidth" class="bg-blue">
                  <el-form-item label-width="80px;" label="结算账户:" prop="accountId" style="width:100%">
                    <SelectAccount
                      v-model="dataObj.accountId"
                    />
                  </el-form-item>
                </td>
              </tr>
              <tr>
                <td align="right">
                  <div class="w200">
                    <el-form-item label="应收金额:" prop="amountPayable">
                      {{ dataObj.amountPayable }}
                    </el-form-item>
                  </div>
                </td>
                <td :width="tableFixedWidth" class="bg-blue">
                  <el-form-item label="实收金额:" prop="amountPaid">
                    <el-input v-model.number="dataObj.amountPaid" />
                  </el-form-item>
                  <div class="font12 color-gay clearfix">
                    <span>本单欠款:￥{{ amountDebt }}</span>
                    <span class="fr">累计应收欠款：￥ {{ amountDebtTotal }}</span>
                  </div>
                </td>
              </tr>
              <tr>
                <td style="padding:0;" @mouseenter="onTdMouseEnter" @mouseleave="onTdMouseLeave">
                  <table class="wfull" border="0" cellspacing="0" cellpadding="0">
                    <tr class="lastrow">
                      <td width="100">
                        备 注:
                      </td>
                      <td class="lastCol">
                        <el-input v-model="dataObj.remarks" class="wfull" type="textarea" />
                      </td>
                    </tr>
                  </table>
                </td>
                <td :width="tableFixedWidth" style="padding:0; position: relative; overflow: hidden;">
                  <el-button class="full-button" type="primary" :loading="btnLoading.save" @click="btnSave">保存(Ctrl+S)</el-button>
                </td>
              </tr>
            </table>
          </div>
        </el-card>
      </el-form>
    </el-main>
  </div>
</template>

<script>
import { oftenuse } from '@/libs/mixins'
import { addSale } from '@/api/bill/bill-sale.js'
import { add, update } from './mixins'
import { price, priceCat } from '@/views/bill/sale/mixins'
import { islockstore } from '@/views/bill/mixins'
import GoodsSelect from './GoodsSelect'
import Affix from '@/components/Affix'
import moment from 'moment'
import SelectComego from '@/views/components/SelectComego'
import SelectEmployee from '@/views/components/SelectEmployee'
import SelectAccount from '@/views/components/SelectAccount'
import SelectGoodsBtns from '@/views/components/SelectGoodsBtns'
import DeliveryInfo from '@/views/bill/sale/components/delivery-info.vue'
import clonedeep from 'clonedeep'
import { getSaleType } from '@/api/sys/dict.js'
import { tools } from '@/views/bill/mixins'
import { Discount } from '@/views/bill/sale/components'

export default {
  name: 'SaleAdd',
  components: {
    SelectComego,
    SelectEmployee,
    SelectAccount,
    SelectGoodsBtns,
    GoodsSelect,
    DeliveryInfo,
    Discount,
    Affix
  },
  filters: {
  },
  mixins: [add, update, price, priceCat, oftenuse, islockstore, tools],
  props: {
    billId: {
      type: String,
      default: null
    },
    operation: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      billExtSale: {},
      optionsData: { saleType: [] },
      ruleValidator: {
        handUserId: [{ required: true, message: '请选择经手人！', trigger: 'change' }],
        comegoId: [{ required: true, message: '请选择客户', trigger: 'change' }],
        accountId: [{ required: true, message: '请选择结算账户', trigger: 'change' }],
        amountPaid: [
          { validator: (rule, value, callback) => {
            const amountPayable = this.dataObj.amountPayable
            if (value > amountPayable) return callback(new Error(`金额不能大于${amountPayable}`))
            callback()
          } }
        ]
      },
      tableFixedWidth: 300,
      goodsSelectComp: null
    }
  },
  computed: {
    'isOpenDiscount': function() {
      const businessSetup = this.appData.businessSetup || {}
      return businessSetup.isOpenDiscount
    }
  },
  mounted() {
    this.goodsSelectComp = this.$refs.GoodsSelect
  },
  created() {
    this.initData()
  },
  methods: {
    btnJump2List() {
      this.jump2List()
    },
    btnSave({ readd }) {
      const billDetailList = clonedeep(this.$refs.GoodsSelect.getPostData())
      const bill = clonedeep(this.dataObj)
      this.handleVali({ bill, billDetailList }).then(_ => {
        const params = {
          bill,
          billExtSale: this.billExtSale,
          billDetailList
        }
        this.setBtnLoading('save', true)
        this.saveData(params).then((res) => {
          this.setBtnLoading('save', false)
          if (!res.data.flag) {
            return this.$notify.error({ title: '保存失败！', message: res.data.message })
          }
          if (readd) {
            this.resetData()
          } else {
            this.jump2List()
          }
        }).catch(err => {
          console.log(err)
          this.setBtnLoading('save', false)
        })
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // api
    getSaleType() {
      getSaleType().then(data => {
        this.$set(this.optionsData, 'saleType', data)
      })
    },
    jump2List() {
      this.closeCurrentTag(this.$route)
      this.$router.push({
        name: 'SaleList',
        params: { refresh: true }
      })
    },
    handleVali({ bill, billDetailList }) {
      const v1 = this.handleValiData({ bill, billDetailList })
      const v2 = this.handleValid('billForm')
      const v3 = this.$refs.GoodsSelect.valiData()
      return Promise.all([v1, v2, v3])
    },
    handleValiData({ bill, billDetailList }) {
      return new Promise((resolve, reject) => {
        if (billDetailList.length === 0) {
          reject(new Error('请录入需要销售的商品！'))
          return
        }
        resolve()
      })
    },
    initData() {
      if (this.operation === 'add') this.initSaveData()
      if (this.operation === 'update') this.initUpdateData()
      if (this.operation === 'transadd') {
        this.initUpdateData().then(_ => {
          this.getBillCode()
          const date = moment().format('YYYY-MM-DD HH:mm:ss')
          this.$set(this.dataObj, 'businessTime', date)
        })
      }
      if (this.operation === 'copyadd') {
        this.initUpdateData().then(_ => {
          this.getBillCode()
          const date = moment().format('YYYY-MM-DD HH:mm:ss')
          this.$set(this.dataObj, 'businessTime', date)
          this.$set(this.dataObj, 'id', null)
        })
      }
    },
    /**
     * 保存采购订单
     */
    saveData(params) {
      return new Promise((resolve, reject) => {
        addSale(params).then(res => {
          resolve(res)
          if (res.data.flag) {
            this.jump2List()
            return this.$notify.success({ title: '保存成功！' })
          }
        }).catch(err => {
          this.$notify.error({ title: '保存异常！', message: err || '' })
          reject(err)
        })
      })
    },
    /**
     * 重置数据
     */
    resetData() {
      this.initSaveData()
    },
    // on
    onTdMouseEnter(e) {
      const target = e.target
      target.className = 'bg-gay'
    },
    onTdMouseLeave(e) {
      const target = e.target
      target.className = ''
    },
    onCustomerChange(data) {
      const { id, name } = data
      this.$set(this.dataObj, 'comegoId', id)
      this.$set(this.dataObj, 'comegoName', name)
    },
    onSelectGoodsSure(_data) {
      const data = clonedeep(_data)
      if (!this.isOpenDiscount) {
        this.$refs.GoodsSelect.pushTableData(data)
        return
      }
      // 没有等级
      data.forEach(item => {
        item.discount = this.$amount(100).format()
        item.priceDef = item.price
      })
      this.$refs.GoodsSelect.pushTableData(data)
    }
  }
}
</script>
<style lang="scss" scoped>
 .dis-count-type{
   /deep/.el-input__inner{width: 150px;}
 }
</style>
